package cn.pconline.officialclub.web.cms;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.SubjectService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Result;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.officialclub.entity.OActivity;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubTag;
import cn.pconline.officialclub.service.OActivityService;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.OClubTagService;
import cn.pconline.officialclub.service.OStatService;
import cn.pconline.officialclub.web.WebKit;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author xulin
 */
@RequestMapping(value = "/brand/cms")
@Controller
public class CmsOClubController extends WebKit {

    @Autowired
    private OClubService oClubService;
    @Autowired
    private OActivityService oActivityService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private OClubTagService oClubTagService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private OStatService oStatService;

    /**
     * 车友会首页接口(我的品牌车友会)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listMyOfficialClub.do", method = RequestMethod.GET)
    public void listMyOfficialClub(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int pageNo = WebUtils.paramInt(request, "pageNo", DEF_PAGE_NUM);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEF_PAGE_SIZE, DEF_MIN_PAGESIZE, DEF_MAX_PAGESIZE);
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        User user = userAuth.getUser(request, response);
        boolean isXss = xssEncode == XSSENCODECODE;
        JSONObject object = new JSONObject();
        if (user == null || user.getUid() == 0) {
            printMsg(response, Result.noLogin(), callback);
            return;
        }
        Pager<OClub> pager = oClubService.pagerClubJoin(user.getUid(), pageNo, pageSize);
        JSONArray array = new JSONArray();
        if (pager != null && pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            for (OClub oClub : pager.getResultList()) {
                OActivity oActivity = oActivityService.getLatestActivity(oClub.getoClubId());
                JSONObject c = oClub.getJSON(isXss);
                if (oActivity != null && oActivity.getEndDate().after(DateUtils.getNow())) {
                    JSONObject o = oActivity.getJSONFilterUbb(isXss);
                    o.put("url", systemConfig.getBrandClubRoot() + "/" + oClub.getUrl() + "/activity/a" + oActivity.getActivityId() + "/");
                    o.put("statusCode", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityCode"));
                    o.put("statusMsg", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityMsg"));
                    c.put("activity", o);
                }
                array.add(c);
            }
        }
        printMsg(response, Result.success(array), callback);
    }

    /**
     * 根据ID列表查询品牌车友会(汇总页)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listOfficialClubByIds.do", method = RequestMethod.GET)
    public void listOfficialClubByIds(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        String[] ids = WebUtils.param(request, "ids", "").split(",");
        String callback = WebUtils.param(request, "callback", "");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        WebUtils.setEncoding(request, response);
        List<Object> idList = new ArrayList<Object>(ids.length);
        for (String s : ids) {
            try {
                int i = Integer.parseInt(s);
                if (i > 0) {
                    idList.add(i);
                }
            } catch (java.lang.NumberFormatException e) {
                continue;
            }
        }
        JSONArray array = new JSONArray();
        if (!idList.isEmpty()) {
            List<OClub> oClubs = oClubService.listClubByIds(idList.toArray());
            if (oClubs != null && !oClubs.isEmpty()) {
                for (OClub oClub : oClubs) {
                    JSONObject o = oClub.getJSON(xssEncode == XSSENCODECODE);
                    int tagId = o.getIntValue("tagId");
                    OClubTag oClubTag = oClubTagService.findById(OClubTag.class, tagId);
                    if (oClubTag != null) {
                        o.put("tagName", oClubTag.getTagName());
                    }
                    array.add(o);
                }
            }
        }
        printMsg(response, Result.success(array), callback);
    }

    /**
     * 根据活动ID查询活动列表(品牌车友会汇总页)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listActivityByIds.do", method = RequestMethod.GET)
    public void listActivityByIds(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        String[] ids = WebUtils.param(request, "ids", "").split(",");
        String callback = WebUtils.param(request, "callback", "");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        WebUtils.setEncoding(request, response);
        List<Object> idList = new ArrayList<Object>(ids.length);
        int MIN_CONTENT_LENGTH = 150;
        for (String s : ids) {
            try {
                int i = Integer.parseInt(s);
                if (i > 0) {
                    idList.add(i);
                }
            } catch (java.lang.NumberFormatException e) {
                continue;
            }
        }
        JSONArray array = new JSONArray();
        if (!idList.isEmpty()) {
            List<OActivity> list = oActivityService.listActivity(ids);
            if (list != null && !list.isEmpty()) {
                oClubService.loadClub(list);
                for (OActivity oActivity : list) {
                    OClub oClub = oActivity.getoClub();
                    JSONObject o = oActivity.getJSONFilterUbb(isXss);
                    if (oClub != null) {
                        o.put("url", systemConfig.getBrandClubRoot() + "/" + oClub.getUrl() + "/activity/a" + oActivity.getActivityId() + "/");
                        o.put("clubUrl", oClub.getUrl());
                        o.put("statusCode", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityCode"));
                        o.put("statusMsg", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityMsg"));
                        //当活动内容过滤图片表情后长度不够时读取更多内容
                        if (oActivity.getLongContent() == OActivity.HAS_LONGCONTENT && o.getString("content").length() < MIN_CONTENT_LENGTH) {
                            o.put("content", EncodeUtils.encodeForHTML(WebUtils.byteSubstring4Reply(oActivityService.getActivityContent(oActivity.getActivityId(), 3)), isXss));
                        }
                    }
                    array.add(o);
                }
            }
        }
        printMsg(response, Result.success(array), callback);
    }

    /**
     * 根据车系ID查询品牌车友会(文章页面接口)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listOfficialClubBySeriesId.do", method = RequestMethod.GET)
    public void listOfficialClubBySeriesId(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        long seriesId = WebUtils.paramLong(request, "seriesId", 0);
        String callback = WebUtils.param(request, "callback", "");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        if (seriesId == 0) {
            printMsg(response, Result.dataError("缺少车系ID"));
            return;
        }
        OClub oClub = oClubService.queryClubBySeriesId(seriesId);
        JSONObject obj = new JSONObject();
        if (oClub != null) {
            obj = oClub.getJSON(isXss);
            OActivity oActivity = oActivityService.getLatestActivity(oClub.getoClubId());
            if (oActivity != null && oActivity.getEndDate().after(DateUtils.getNow())) {
                JSONObject o = oActivity.getJSONFilterUbb(isXss);
                o.put("url", systemConfig.getBrandClubRoot() + "/" + oClub.getUrl() + "/activity/a" + oActivity.getActivityId() + "/");
                o.put("statusCode", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityCode"));
                o.put("statusMsg", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityMsg"));
                obj.put("activity", o);
            }
            List<Club> clubs = clubService.getListBySeriesId(seriesId, 1, 3);
            JSONArray array = new JSONArray();
            if (clubs != null && !clubs.isEmpty()) {
                for (Club club : clubs) {
                    array.add(isXss ? club.toJsonEncodeHTML() : club.toJson());
                }
            }
            obj.put("club", array);
        }
        printMsg(response, Result.success(obj), callback);
    }

    /**
     * 热门圈子排行榜(车友会首页排行版)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listHotCyq.do", method = RequestMethod.GET)
    public void listHotCyq(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int num = WebUtils.paramInt(request, "num", 10);
        if (num > 20) {
            num = 10;
        }
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        List<OClub> list = oClubService.listClubByTag(OClubTag.CYQ, num);
        JSONArray arr = new JSONArray();
        for (OClub club : list) {
            JSONObject o = new JSONObject();
            o.put("name", EncodeUtils.encodeForHTML(club.getName(), isXss));
            o.put("oClubId", club.getoClubId());
            o.put("url", club.getUrl());
            o.put("clubUrl", systemConfig.getBrandClubRoot() + "/" + club.getUrl() + "/");
            o.put("logo150x150", club.getLogo150x150());
            o.put("memberNum", club.getMemberNum());
            o.put("niceMemberNum",
                    club.getMemberNum() > 10000
                    ? (club.getMemberNum() / 100 + 5) / 10 / 10.0 + "万" : club.getMemberNum());
            arr.add(o);
        }
        printMsg(response, Result.success(arr), callback);
    }

    /**
     * 热门话题排行榜(车友会首页排行版)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listHotSubject.do", method = RequestMethod.GET)
    public void listHotSubject(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int num = WebUtils.paramInt(request, "num", 10);
        if (num > 20) {
            num = 10;
        }
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        Date beginDate = DateUtils.getSingleDateBefore(new Date(), 7);
        Pager<Subject> pager = subjectService.pageSubjectByHot(1, num, beginDate);
        List<Subject> list = pager.getResultList();
//        List<Subject> list = subjectService.listSubject(num);
        JSONArray arr = new JSONArray();
        for (Subject s : list) {
            JSONObject o = new JSONObject();
            o.put("subjectId", s.getSubjectId());
            o.put("title", EncodeUtils.encodeForHTML(s.getTitle(), isXss));
            o.put("subjecUrl", systemConfig.getRoot() + "/topic/" + s.getSubjectId() + ".html");
            o.put("logo", StringUtils.isBlank(s.getLogo()) ? s.getDefaultLogo() : s.getLogo());
            o.put("pvCount", s.getPvCount());
            o.put("nicePvCount",
                    s.getPvCount() > 10000
                    ? (s.getPvCount() / 100 + 5) / 10 / 10.0 + "万" : s.getPvCount());
            arr.add(o);
        }
        printMsg(response, Result.success(arr), callback);
    }

    /**
     * 车友会首页通栏接口
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listClubByIds.do", method = RequestMethod.GET)
    public void listClubByIds(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        List<Long> ids = WebUtils.paramLongs(request, "ids");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        List<OClub> list = oClubService.listClubByIds(ids.toArray());
        JSONArray arr = new JSONArray();
        for (OClub club : list) {
            JSONObject o = new JSONObject();
            o.put("name", EncodeUtils.encodeForHTML(club.getName(), isXss));
            o.put("oClubId", club.getoClubId());
            o.put("url", club.getUrl());
            o.put("clubUrl", systemConfig.getBrandClubRoot() + "/" + club.getUrl() + "/");
            o.put("logo150x150", club.getLogo150x150());
            o.put("memberNum", club.getMemberNum());
            arr.add(o);
        }
        printMsg(response, Result.success(arr), callback);
    }

    /**
     * wap首页和wap车友会首页接口
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listClubByIds4wap.do", method = RequestMethod.GET)
    public void listClubByIds4wap(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        List<Long> ids = WebUtils.paramLongs(request, "ids");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        List<OClub> list = oClubService.listClubByIds(ids.toArray());
        JSONArray arr = new JSONArray();
        for (OClub club : list) {
            JSONObject o = new JSONObject();
            o.put("name", EncodeUtils.encodeForHTML(club.getName(), isXss));
            o.put("oClubId", club.getoClubId());
            o.put("url", club.getUrl());
            o.put("clubUrl", systemConfig.getBrandClubWapRoot() + "/" + club.getUrl() + "/");
            o.put("logo150x150", club.getLogo150x150());
            o.put("memberNum", club.getMemberNum());
            o.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), isXss));
            arr.add(o);
        }
        printMsg(response, Result.success(arr), callback);
    }

    /**
     * 车友会首页通栏接口
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listSubjectByIds.do", method = RequestMethod.GET)
    public void listSubjectByIds(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        List<Long> ids = WebUtils.paramLongs(request, "ids");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        List<Subject> list = subjectService.listSubjectByIds(ids.toArray());
        JSONArray arr = new JSONArray();
        for (Subject s : list) {
            JSONObject o = new JSONObject();
            o.put("subjectId", s.getSubjectId());
            o.put("title", EncodeUtils.encodeForHTML(s.getTitle(), isXss));
            o.put("subjecUrl", systemConfig.getRoot() + "/topic/" + s.getSubjectId() + ".html");
            o.put("logo", StringUtils.isBlank(s.getLogo()) ? s.getDefaultLogo() : s.getLogo());
            o.put("pvCount", s.getPvCount());
            o.put("replyCount", s.getReplyCount());
            arr.add(o);
        }
        printMsg(response, Result.success(arr), callback);
    }

    /**
     * wap首页论坛模块下方热门话题接口
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/listSubjectByIds4wap.do", method = RequestMethod.GET)
    public void listSubjectByIds4wap(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        List<Long> ids = WebUtils.paramLongs(request, "ids");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        List<Subject> list = subjectService.listSubjectByIds(ids.toArray());
        JSONArray arr = new JSONArray();
        for (Subject s : list) {
            JSONObject o = new JSONObject();
            o.put("subjectId", s.getSubjectId());
            o.put("title", EncodeUtils.encodeForHTML(s.getTitle(), isXss));
            o.put("createAt", DateUtils.format(s.getCreateAt()));
            o.put("subjecUrl", systemConfig.getWapRoot() + "/topic/" + s.getSubjectId() + ".html");
            o.put("logo", StringUtils.isBlank(s.getLogo()) ? s.getDefaultLogo() : s.getLogo());
            o.put("pvCount", s.getPvCount());
            o.put("replyCount", s.getReplyCount());
            arr.add(o);
        }
        printMsg(response, Result.success(arr), callback);
    }

    /**
     * wap车友会首页|wap汽车网首页(接口)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/getOfficialClubByCityId4wap.do", method = RequestMethod.GET)
    public void getOfficialClubByCityId4wap(HttpServletRequest request, HttpServletResponse response) {
        //设置缓存
        WebUtils.setCacheHeader(response, 3600);
        WebUtils.setEncoding(request, response);
        long cityId = WebUtils.paramLong(request, "cityId", 0);
        long provinceId = WebUtils.paramLong(request, "provinceId", 0);
        String callback = WebUtils.param(request, "callback", "");
        int xssEncode = WebUtils.paramInt(request, XSS_ENCODE, XSSENCODECODE);
        boolean isXss = xssEncode == XSSENCODECODE;
        if (cityId == 0 && provinceId == 0) {
            printMsg(response, Result.dataError("缺少城市ID"));
            return;
        }
        OClub oClub = null;
        if (cityId != 0 && cityId != provinceId) {
            oClub = oClubService.findClubByCityId(cityId);
        }
        if ((cityId == 0 && provinceId != 0) || cityId == provinceId) {
            oClub = oClubService.findClubByProvinceId(provinceId);
        }
        JSONObject obj = new JSONObject();
        if (oClub != null) {
            obj = oClub.getJSON(isXss);
            obj.put("clubUrl", systemConfig.getBrandClubWapRoot() + "/" + oClub.getUrl() + "/");
            OActivity oActivity = oActivityService.getLatestActivity(oClub.getoClubId());
            if (oActivity != null) {
                JSONObject o = oActivity.getJSONFilterUbb(isXss);
                o.put("url", systemConfig.getBrandClubWapRoot() + "/" + oClub.getUrl() + "/activity/a" + oActivity.getActivityId() + "/");
                o.put("statusCode", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityCode"));
                o.put("statusMsg", oActivityService.getActivityStatusDesc(0, oActivity).getString("activityMsg"));
                obj.put("activity", o);
            }
            obj.put("clubPv", oStatService.countPvByClubId(oClub.getoClubId()));
        }
        printMsg(response, Result.success(obj), callback);
    }
}
